<template>
  <div class="app-container">
    <el-card>
      <div slot="header" class="disFlxJS">
        <span class="fw-7">
          <span>订单信息</span>
          <span class="fz-14 colorRED ml-10">{{ order_tuikuanjinge(info) }}</span>
          <span class="fz-12 color9 ml-10" v-if="order_tuikuanjinge(info) && info.refundRemark">({{ info.refundRemark }})</span>
        </span>
        <div>
          <el-button-group>
            <el-button
              v-if="nonPayment(info) && hasPermiAnd(['order:inspection:nonPayment'])"
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click="openOrderPlay(info)"
              >立即收款</el-button
            >
            <el-button
              v-if="whetherSettle(info) && hasPermiAnd(['order:inspection:whetherSettle'])"
              type="primary"
              size="mini"
              icon="el-icon-money"
              @click="openSettle"
              >立即核销</el-button
            >
            <el-button
              v-if="whetherConsignment(info) && hasPermiAnd(['order:inspection:whetherConsignment'])"
              type="primary"
              size="mini"
              icon="el-icon-truck"
              @click="openLogistics(info.id, info.mailingInfo.id)"
              >立即发货</el-button
            >
            <el-button
              v-if="showCancelOrder(info) && hasPermiAnd(['order:inspection:showCancelOrder'])"
              type="primary"
              size="mini"
              icon="el-icon-document-delete"
              @click="cancelOrder(info)"
              >取消订单</el-button
            >
          </el-button-group>
        </div>
      </div>
      <el-descriptions :column="2" border :labelStyle="{width: '120px'}" :contentStyle="{width: '480px'}">
        <el-descriptions-item label="订单编号">{{info.orderNo}}</el-descriptions-item>
        <el-descriptions-item label="状态" labelClassName="linh-28">
          <div class="disFlxAC">
            <dict-tag :options="dict.type.order_status" :value="info.status" />
            <div
              v-if="getMedicationStatusTitle(info)"
              class="ml-10"
              :style="{ color: getMedicationStatusTitle(info).color }"
            >
              ({{ getMedicationStatusTitle(info).title }})
            </div>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="开单申请人">{{info.sponsor}}</el-descriptions-item>
        <el-descriptions-item label="申请人所属机构">{{info.companyName}}</el-descriptions-item>
        <el-descriptions-item label="消费人信息">
          <template v-if="info.parescriptOrder && info.parescriptOrder.patientName">
            <span>{{ info.parescriptOrder.patientName}}<span class="px-2">/</span></span>
            <span>{{ info.parescriptOrder.patientSex === 1 ? "女" : "男"}}<span class="px-2">/</span></span>
            <span>{{ info.parescriptOrder.patientAge }}岁<span class="px-2">/</span></span>
            <span>{{ info.parescriptOrder.patientPhone }}</span>
          </template>
          <template v-else>
            <span>{{ info.username }}<span class="px-2">/</span></span>
            <span>{{ info.userphone }}</span>
          </template>
        </el-descriptions-item>
        <el-descriptions-item label="服务所属机构">{{info.checkAgencyName}}</el-descriptions-item>
        <el-descriptions-item label="订单归属渠道">{{info.channelName}}</el-descriptions-item>
        <el-descriptions-item label="订单归属业务员">{{info.businessUserName}}</el-descriptions-item>

        <el-descriptions-item v-if="whetherSettle(info) || info.checkStatus == 1 || info.checkStatus == 2" label="订单核销状态" labelClassName="linh-28">
          <el-tag v-if="info.checkStatus == 2" plain>部分核销</el-tag>
          <el-tag v-else-if="info.checkStatus == 1" plain>已核销</el-tag>
          <el-tag v-else-if="whetherSettle(info)" type="warning"plain>待核销</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <div class="mt-10"></div>
      <el-descriptions :column="2" border :labelStyle="{width: '120px'}" :contentStyle="{width: '480px'}">
        <el-descriptions-item label="订单金额">
          <div class="colorY">￥{{ order_dingdanjinge(info) }}</div>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{info.createTime}}</el-descriptions-item>
      </el-descriptions>

      <!-- （发起方订单 && 中医订单显示） || （服务商订单 && 中医贴敷订单显示） -->
      <template v-if="info.status != 1 && info.status != 5">
        <el-descriptions v-if="(info.start === '1' && info.orderSource === 1) || (info.start === '0' && info.parescriptOrder && info.parescriptOrder.prescriptionType == 1)" :column="2" border :labelStyle="{width: '120px'}" :contentStyle="{width: '480px'}">
          <el-descriptions-item label="实收金额">
            <div v-if="info.collectCost || info.collectCost === 0" class="colorY">￥{{ info.collectCost }}</div>
            <div v-else>-</div>
          </el-descriptions-item>
          <el-descriptions-item label="收款方式">
            <div v-if="info.collectWay">
              <span>线下收款</span>
              <span class="ml-10">({{ info.collectWay }})</span>
            </div>
            <div v-else>-</div>
          </el-descriptions-item>
          <el-descriptions-item label="收款时间">{{ info.collectCostTime || "-" }}</el-descriptions-item>
          <el-descriptions-item label="收款人">{{info.payeeUser || "-"}}</el-descriptions-item>
        </el-descriptions>

        <!-- 服务商订单- 只显示实付金额，支付方式，支付时间 -->
        <el-descriptions v-if="!info.parescriptOrder || info.parescriptOrder.prescriptionType != 1" :column="2" border :labelStyle="{width: '120px'}" :contentStyle="{width: '480px'}">
          <el-descriptions-item label="实付金额">
            <div v-if="order_shifujinge(info) || order_shifujinge(info) === 0" class="colorY">￥{{ order_shifujinge(info) }}</div>
            <div v-else>-</div>
          </el-descriptions-item>
          <el-descriptions-item label="支付方式">
            <span>{{ getPlayTypeTitle(info) }}</span>
            <span v-if="info.payWaySet" class="ml-10">({{ info.payWaySet }})</span>
          </el-descriptions-item>
          <el-descriptions-item label="支付时间">{{info.playCreateTime || "-"}}</el-descriptions-item>
        </el-descriptions>
      </template>
    </el-card>


    <el-card class="mt-20">
      <div slot="header">
        <span class="fw-7">处方信息</span>
      </div>
      <div class="girdBox">
        <div
          v-for="(item, index) in info.sheetList"
          :key="index"
          class="printOrder fz-14"
        >
          <div class="relative">
            <ParescriptNum :info="info" :serviceDetailIndex="index" />
            <div class="absolute" style="top: 0;right: 0;">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-printer"
                @click="print(item, index)"
                >打印预览</el-button
              >
            </div>
          </div>
          <ParescriptType :info="info" :prescriptionInfo="item" class="my-5">
            <div v-if="info.parescriptOrder && info.parescriptOrder.status === 3" class="disFlx py-3">
              <span class="fw-7 shrink0">是否取药：</span>
              <span style="color: #67c23a">(已取药)</span>
            </div>
            <div v-else-if="info.parescriptOrder && info.parescriptOrder.status !== -1" class="disFlx py-3">
              <span class="fw-7 shrink0">是否取药：</span>
              <span class="pl-10" style="color: #f56c6c">(未取药)</span>
            </div>
            <div v-if="info.orderSource != 1" class="disFlx py-3">
              <span class="fw-7 shrink0">小计：</span>
              <span><span class="fw-6 colorY">{{ item.subCost }}</span> 云豆</span>
            </div>
          </ParescriptType>

          <ParescriptItem :info="info" :prescriptionInfo="item" :printConfig="printConfig" />
        </div>
      </div>
    </el-card>
    <el-card v-if="info.mailingInfo && info.parescriptOrder" class="mt-20">
      <div slot="header">
        <span class="fw-7">备注信息</span>
      </div>
      <el-descriptions :column="1" border :labelStyle="{width: '120px'}">
        <el-descriptions-item label="药房备注">
          <span>{{info.parescriptOrder.pharmacyRemark}}</span>
        </el-descriptions-item>
        <el-descriptions-item label="物流备注">
          <span v-if="info.parescriptOrder.sendPrescript === 1">
            ({{ "需随药发处方单" }})
          </span>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card v-if="info.mailingInfo" class="mt-20">
      <div slot="header">
        <span class="fw-7">快递物流</span>
      </div>
      <el-descriptions :column="1" border :labelStyle="{width: '120px'}">
        <el-descriptions-item label="收件人信息">
           <div>
            <div class="fz-12 linh-20">
              <span class="color6 pr-17">姓 名:</span>
              <span>{{ info.mailingInfo.recipientName || "-" }}</span>
            </div>
            <div class="fz-12 linh-20">
              <span class="color6 pr-5">手机号:</span>
              <span>{{ info.mailingInfo.recipientPhone || "-" }}</span>
            </div>
            <div class="fz-12 linh-20">
              <span class="color6 pr-17">地 址:</span>
              <span v-if="info.mailingInfo.province || info.mailingInfo.mailingAddr">
                {{ `${info.mailingInfo.province || ""} ${info.mailingInfo.mailingAddr || ""}`}}
              </span>
              <span v-else>-</span>
            </div>
          </div>
        </el-descriptions-item>

        <el-descriptions-item label="物流信息">
          <span class="fw-7 fz-12 pt-10">{{ getLogisticInfoTitle(info) }}</span>
          <div>
            <div class="fz-12 linh-20">
              <span class="color6 pr-17">快递公司:</span>
              <span>{{ info.mailingInfo.expressBrand || "-" }}</span>
            </div>
            <div class="fz-12 linh-20">
              <span class="color6 pr-17">快递单号:</span>
              <span>{{ info.mailingInfo.expressNumber || "-" }}</span>
            </div>
          </div>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <el-card class="mt-20">
      <div slot="header">
        <span class="fw-7">核销记录</span>
      </div>
      <!-- <el-radio-group v-model="controlsTabsType" size="small">
        <el-radio-button :label="0">发货记录</el-radio-button>
        <el-radio-button :label="1">核销记录</el-radio-button>
      </el-radio-group> -->
      <el-table :data="controlsList">
        <el-table-column
          label="核销时间"
          prop="createTime"
          width="160"
          align="center"
        >
        </el-table-column>
        <el-table-column
          label="核销人"
          prop="auditUser"
          width="140"
          align="center"
        >
        </el-table-column>
        <el-table-column label="核销项目" align="center">
          <template slot-scope="{ row }">
            <div v-html="row.auditProject"></div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div style="display: none">
      <div ref="printOrder">
        <PrintDom
          :info="info"
          :printConfig="printConfig"
          :prescriptionInfo="prescriptionInfo"
          :serviceDetailIndex="serviceDetailIndex"
        />
      </div>
    </div>

    <OrderPlay ref="OrderPlay" @refresh="getOrderDetail" />
    <Logistics ref="Logistics" @refresh="getOrderDetail" />
    <WriteOff ref="WriteOff" @refresh="getOrderDetail" />
    <CancelOrder ref="CancelOrder" @refresh="getOrderDetail" />
  </div>

  <!-- <div>
    <span>总计: </span>
    <span class="px-2 fw-6 colorY">{{ info.costOriginal }}</span>
    <span class="pr-10">云豆</span>
    <template v-if="info.orderSource != 1">
      <span>优惠：</span>
      <span class="px-2 fw-6 colorY">{{
        info.costOriginal === info.cost ||
        numSub(info.costOriginal, info.cost) < 0
          ? 0
          : numSub(info.costOriginal, info.cost)
      }}</span>
      <span class="pr-10">云豆</span>

      <span>应付: </span>
      <span class="px-2 fw-6 colorY">{{ info.cost }}</span>
      <span>云豆</span>
    </template>
  </div> -->
</template>

<script>
import { numSub } from "@/utils/big/calculate.js";
import { Print } from "@/utils/print";
import { checkAuditList, orderDetail } from "@/api/service";
import PrintDom from '../components/print.vue'
import OrderPlay from '../components/orderPlay.vue'
import Logistics from '../components/logistics.vue';
import WriteOff from '../components/writeOff.vue';
import CancelOrder from '../components/cancelOrder.vue'
import { whetherSettle, nonPayment, showSettlement, whetherConsignment, showCancelOrder, getMedicationStatusTitle, getLogisticInfoTitle, getPlayTypeTitle, order_dingdanjinge, order_shifujinge, order_tuikuanjinge } from '../components/mixin.js'
import { hasPermiAnd } from '@/plugins/auth'
import ParescriptNum from '../components/prescription/num.vue'
import ParescriptType from '../components/prescription/type.vue'
import ParescriptItem from '../components/prescription/item.vue'

export default {
  name: "InspectionDetails",
  dicts: ["order_status"],
  components: {
    PrintDom,
    OrderPlay,
    Logistics,
    WriteOff,
    CancelOrder,
    ParescriptNum,
    ParescriptType,
    ParescriptItem
  },
  data() {
    return {
      info: {
        id: undefined,
        childOrderId: undefined
      }, // 订单详情
      unitList: [],
      controlsTabsType: 1,
      controlsList: [],  // 发货记录 + 核销记录

      prescriptionInfo: null,
      serviceDetailIndex: 0, // 处方号所在的下标
      printConfig: {},
    };
  },
  created() {
    this.getOrderDetail();
  },
  methods: {
    numSub,
    whetherSettle,
    nonPayment,
    showSettlement,
    whetherConsignment,
    showCancelOrder,
    getMedicationStatusTitle,
    getLogisticInfoTitle,
    getPlayTypeTitle,
    order_dingdanjinge,
    order_shifujinge,
    order_tuikuanjinge,
    hasPermiAnd,
    getOrderDetail() {
      const { id, childOrderId } = this.$route.query;
      orderDetail({ orderId: id, childOrderId: childOrderId }).then(res => {
        this.info = res.data;
        // 查看核销记录
        checkAuditList({ orderNo: this.info.orderNo }).then((res) => {
          this.controlsList = this.mergeControlsList(res.rows);
        });
      })
    },

     mergeControlsList(rows) {
      const mergedData = {};
      rows.forEach(row => {
        const { operateNo, auditProject: auditProjectBefore = '', ...rest } = row;
        const auditProject = auditProjectBefore.includes('<br/>') ? auditProjectBefore : `${auditProjectBefore}<br/>`;

        console.log();

        if (!mergedData[operateNo]) {
          mergedData[operateNo] = { ...rest, auditProject: [auditProject] };
        } else {
          mergedData[operateNo].auditProject.push(auditProject);
        }
      });
      // 将对象转换回数组
      return Object.values(mergedData).map(row => ({
        ...row,
        auditProject: row.auditProject.join('') // 或者使用其他分隔符
      }))
    },
    // 打开核销弹窗
    openSettle() {
      this.$refs.WriteOff.openModal(this.info);
    },
    // 去收款
    openOrderPlay(info) {
      this.$refs.OrderPlay.show(info)
    },
    // 去发货
    openLogistics(orderId, id) {
      this.$refs.Logistics.openModal(orderId, id)
    },
    // 取消订单
    cancelOrder(row) {
      this.$refs.CancelOrder.openModal(row)
    },
    print(item, index) {
      this.prescriptionInfo = item;
      this.serviceDetailIndex = index;
      const printConfig = localStorage.getItem("printConfig");
      this.printConfig = printConfig ? JSON.parse(printConfig) : {};

      this.$nextTick(() => {
        Print(this.$refs.printOrder);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.colorY {
  color: #bb9313;
}

.disFlxC {
  display: flex;
  flex-direction: column;
  height: 100%;
}
</style>
